package cn.lanqiao.facelogin.utils;

import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * @author 刘磊
 * 2022/2/23  11:04
 */

@Component
public class GenerateImage {
    /**
     * base64字符串转化成图片
     *
     * @param imgData     图片编码
     * @param imgFilePath 存放到本地路径
     * @return
     * @throws IOException
     */
    @SneakyThrows
    public boolean generateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        // 图像数据为空
        if (imgData == null) return false;
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedOutputStream out = null;
        out = new BufferedOutputStream(new FileOutputStream(imgFilePath));
        // Base64解码
        byte[] b = decoder.decodeBuffer(imgData);
        for (int i = 0; i < b.length; ++i) {
            // 调整异常数据
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        out.write(b);
        out.flush();
        out.close();
        return new File(imgFilePath).exists();
    }
}
